from django.shortcuts import render,redirect,HttpResponse
from host import models
import json
# Create your views here.
def index(request):
    if request.method == "GET":
        v1 = models.Host.objects.all()
        bussin_info = models.Business.objects.all()
        v2 = models.Host.objects.values('nid', 'name', 'ip', 'port','business__code','business__caption') #字典
        v3 = models.Host.objects.values_list('nid', 'name', 'ip', 'port', 'business__code', 'business__caption') #元祖
        return render(request,'host_index.html',{'v1':v1,'v2':v2,'v3':v3,'bussin_info':bussin_info})
    elif request.method == "POST":
        rt_msg = {'status':True,'error_msg':None}
        try:
            department_id = request.POST.get('department') #部门 ，html里面设置了value提交过来是id了
            host = request.POST.get('host')
            ip = request.POST.get('ip')
            port = request.POST.get('port')
            print(department_id)
            if host and len(host)>4:
                models.Host.objects.create(name=host,
                                           ip=ip,
                                           port=port,
                                           business_id=department_id)
            else:
                rt_msg['status']=False
                rt_msg['error_msg']='太短'

        except Exception as e:
            rt_msg['status'] = False
            rt_msg['error_msg']=str(e)

        return HttpResponse(json.dumps(rt_msg))
def app(request):

    # applist = models.Application.objects.all()
    # for i in applist:
    #     print(i.name,"-->",i.r.all())
    if request.method == "GET":
        v1 = models.Application.objects.all()
        host = models.Host.objects.all()
        return render(request,'app.html',{'v1':v1,'host':host})
    elif request.method == "POST":
        rt_msg = {'status':True,'error_msg':None}
        try:
            if request.POST.get('edit_application'):
                appname = request.POST.get('hid')
                print('hid',appname)

            else:
                application = request.POST.get('application') #部门 ，html里面设置了value提交过来是id了
                host = request.POST.getlist('host')
                print(host)
                obj = models.Application.objects.get(name=application)
                print(obj.name)
                obj.r.add(*host)
        except Exception as e:
            rt_msg['status'] = False
            rt_msg['error_msg']=str(e)

        return HttpResponse(json.dumps(rt_msg))
    # host = request.POST.get('host')
    # application = request.POST.get_list('application')
    # print(host)
    # print(application)




